/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package horsechess.server.data;

import horsechess.server.gui.GUIServer;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 *
 * @author Nguyen Hoang Thinh
 * Email : hoangthinh1989@gmail.com
 */
public class BroadcastServer implements Runnable {

    private int port;
    private String serverAddr;
    private GUIServer guiServer;

    public BroadcastServer(int port, String serverAddr, GUIServer guiServer) {
        this.port = port;
        this.serverAddr = serverAddr;
        this.guiServer = guiServer;
    }

    public void run() {
        broadcast();
    }

    public void broadcast() {

        // Which ttl
        try {
            // Create the socket but we don't bind it as we are only going to send data
            MulticastSocket s = new MulticastSocket();


            String str = new String(port + "");
            byte[] buf = str.getBytes();
            DatagramPacket pack = new DatagramPacket(buf, buf.length,
                    InetAddress.getByName(serverAddr), port);

            // Do a send. Note that send takes a byte for the ttl and not an int.
            serverAddr = pack.getAddress().getHostAddress();
            GUIServer.txtServerStatus.setText("Server is broadcasting message");
            guiServer.updateServerInfo();
            while (true) {
                s.send(pack);
                Thread.sleep(3000);
            }

        } catch (IOException ex) {
            System.err.println("IOException: " + ex.getMessage());
        } catch (InterruptedException ex) {
            System.err.println("Thread error!!!!!!");
        }
    }
}
